/*
 * Copyright 2017-2018 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.micronaut.discovery.client;

import io.micronaut.discovery.ServiceInstance;
import io.micronaut.discovery.ServiceInstanceList;

import java.net.URI;
import java.util.Collections;
import java.util.List;

/**
 * Abstract {@link ServiceInstanceList} implementation for Discovery servers like Eureka and Consul.
 *
 * @author graemerocher
 * @since 1.0
 */
public abstract class DiscoveryServerInstanceList implements ServiceInstanceList {

    private final DiscoveryClientConfiguration configuration;

    /**
     * @param configuration The discovery client configuration
     */
    public DiscoveryServerInstanceList(DiscoveryClientConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public List<ServiceInstance> getInstances() {
        List<ServiceInstance> allZones = configuration.getAllZones();
        if (!allZones.isEmpty()) {
            return allZones;
        } else {
            String spec = (configuration.isSecure() ? "https" : "http") + "://" + configuration.getHost() + ":" + configuration.getPort();
            return Collections.singletonList(
                ServiceInstance.builder(getID(), URI.create(spec)).build()
            );
        }
    }
}
